package com.lijian.dns;

import cn.hutool.core.collection.CollUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsRequest;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsResponse;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsResponse.Record;
import com.aliyuncs.alidns.model.v20150109.UpdateDomainRecordRequest;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * AliDnsService
 *
 * @author LIJIAN
 * @date 2021/2/1
 */
@Slf4j
@Service
public class AliDnsService {

    private static IAcsClient client = null;

    @Value("${aliyun-dns.accessKeyId:}")
    private String accessKeyId;

    @Value("${aliyun-dns.accessKeySecret:}")
    private String accessKeySecret;

    /**
     * 获取DNS客户端
     *
     * @return
     */
    private IAcsClient getClient() {
        if (client == null) {
            String regionId = "cn-hangzhou"; //必填固定值，必须为“cn-hanghou”
            IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
            // 若报Can not find endpoint to access异常，请添加以下此行代码
            // DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Alidns", "alidns.aliyuncs.com");
            client = new DefaultAcsClient(profile);
        }
        return client;
    }

    /**
     * 获取域名解析记录
     * @return
     */
    public List<Record> getRecords(String domainName) {
        try {
            DescribeDomainRecordsRequest request = new DescribeDomainRecordsRequest();
            request.setDomainName(domainName);
            DescribeDomainRecordsResponse response = this.getClient().getAcsResponse(request);
            return response.getDomainRecords();
        } catch (Exception e) {
            log.error(">>>>>>   获取域名解析记录", e);
        }
        return CollUtil.toList();
    }

    /**
     * 解析DNS信息
     */
    public void analysisDns(Record record) {
        UpdateDomainRecordRequest request = new UpdateDomainRecordRequest();
        // 设置参数
        request.putQueryParameter("RecordId", record.getRecordId());
        request.putQueryParameter("RR", record.getRR());
        request.putQueryParameter("Type", record.getType());
        request.putQueryParameter("TTL", record.getTTL());
        request.putQueryParameter("Value", record.getValue());
        try {
            this.getClient().getAcsResponse(request);
        } catch (Exception e) {
            log.error(">>>>>>  域名解析错误: {} {} {}", record.getRR(), record.getValue(), e);
        }
    }

}
